#include "BlockQueue.hpp"
#include "Task.hpp"
#include <time.h>

int myadd(int x,int y)
{
    return x+y;
}

void* consumer(void* args)
{
    BlockQueue<Task>* bque = (BlockQueue<Task>*)args;
    while(1)
    {
        // int a;
        // bque->Pop(&a);
        // std::cout << "消费一个商品: " << a << std::endl;
        // //1:49
        // sleep(1);
        Task t;
        bque->Pop(&t);
        std::cout << "完成任务: " << t._x << "+" << t._y << "=" << t() << std::endl;
    }
    return nullptr;
}

void* productor(void* args)
{
    BlockQueue<Task>* bque = (BlockQueue<Task>*)args;
    while(1)
    {
        // //生产的过程
        // bque->Push(a);
        // std::cout << "生产一个商品:" << a++ << std::endl;
        // int x = rand()%10+1;
        // usleep(1000);
        // int y = rand()%10+1;
        //也可以用IO进行控制
        int x;
        int y;
        std::cout << "请输入x ：";
        std::cin>>x;
        std::cout << "请输入y ：";
        std::cin>>y;
        //构建任务task 
        Task t(x,y,myadd);
        bque->Push(t);
        std::cout << "生产任务: " << t._x << "+" << t._y << "=?" << std::endl;
        sleep(1);
    }
    return nullptr;
}

//基于BlockingQueue的生产消费模型（阻塞队列
int main()
{
    srand((uint64_t)time(nullptr));
    //创建一个阻塞队列
    BlockQueue<Task> *bque = new BlockQueue<Task>();
    //创建线程
    pthread_t c,p;
    pthread_create(&c,nullptr,consumer,bque);
    pthread_create(&p,nullptr,productor,bque);

    pthread_join(c,nullptr);
    pthread_join(p,nullptr);


    delete bque;
    return 0;
}